<template>
  <el-drawer
    v-model="isOpen"
    @close="close"
    :z-index="10"
    :modal="false"
    :lock-scroll="false"
    direction="rtl"
  >
    <template #header>
      <h4>编辑</h4>
    </template>
    <template #default>
      <!-- v-if="formData" 等待数据加载再渲染组件使组件自适应不失效 -->
      <el-form
        v-if="formData"
        :inline="true"
        label-position="top"
        size="small"
        :model="formData"
        class="demo-form-inline"
        :rules="rules"
        ref="formRef"
      >
        <span v-for="(item, index) in editJson" :key="index">
          <el-form-item
            :label="item.label"
            v-if="item.isShow"
            :prop="item.field"
            :style="item.width ? { width: item.width + 'px' } : {}"
          >
            <!--文本-->
            <el-input
              v-if="item.type.value === 'text'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
            />
            <!-- 密码 -->
            <el-input
              v-else-if="item.type.value === 'password'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
              type="password"
              show-password
            />
            <!--文本域-->
            <el-input
              v-if="item.type.value === 'textarea'"
              :disabled="props.editDisables?.includes(item.field)"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 10 }"
              v-model="formData[item.field]"
              clearable
            />
            <!--数字-->
            <el-input-number
              v-else-if="item.type.value === 'number'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
            />
            <!--日期-->
            <el-date-picker
              v-else-if="item.type.value === 'date'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
              type="date"
              style="width: 115px"
            />
            <!--日期时间-->
            <el-date-picker
              v-else-if="item.type.value === 'datetime'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 145px"
            />
            <!--时间-->
            <el-time-picker
              v-else-if="item.type.value === 'time'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
              style="width: 115px"
            />
            <!--开关-->
            <el-switch
              v-else-if="item.type.value === 'switch'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
            />
            <!--选项-->
            <template v-else-if="item.type.value === 'select'">
              <template v-if="optionDatas[item.type.select.optionId]">
                <!-- 树形选项 -->
                <el-tree-select
                  v-if="item.type.select.tree"
                  :disabled="props.editDisables?.includes(item.field)"
                  v-model="formData[item.field]"
                  :data="optionDatas[item.type.select.optionId].options"
                  :multiple="item.type.select.multiple"
                  :render-after-expand="false"
                  show-checkbox
                />
                <el-select
                  v-else
                  :disabled="props.editDisables?.includes(item.field)"
                  :multiple="item.type.select.multiple"
                  :multiple-limit="item.type.select.multipleLimit"
                  v-model="formData[item.field]"
                  filterable
                  default-first-option
                  :allow-create="item.type.select.allowCreate"
                  clearable
                  placeholder="Select"
                  size="small"
                >
                  <el-option
                    v-for="(item, index) in optionDatas[item.type.select.optionId].options"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </template>
            <!--Json-->
            <JsonEditView
              v-else-if="item.type.value === 'json'"
              :disabled="props.editDisables?.includes(item.field)"
              style="width: 600px"
              v-model="formData[item.field]"
            />
            <!--JavaScript-->
            <MonacoEdit
              v-else-if="item.type.value === 'JavaScript'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
              style="width: 600px"
            />
            <!-- 编辑器 -->
            <WangEditorView
              style="width: 600px"
              v-else-if="item.type.value === 'editor'"
              :disabled="props.editDisables?.includes(item.field)"
              v-model="formData[item.field]"
            />
            <!--文件上传-->
            <FileUpload
              v-else-if="item.type.value.includes('upload')"
              v-model:filed="editJson[index]"
              v-model:fileList="fileList"
              :disabled="props.editDisables"
            />
          </el-form-item>
        </span>
        <!-- 编辑字段扩展插槽 -->
        <slot name="EDIT_ADD_FIELD"></slot>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="confirmClick">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { placeholder } from '@/utils/str.js'
import JsonEditView from '@/views/template/util/JsonEditView.vue'
import WangEditorView from '@/views/template/util/WangEditorView.vue'
import MonacoEdit from '@/views/template/util/MonacoEdit.vue'
import FileUpload from './module/FileUpload.vue'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useOptionDataStore } from '@/stores/optionData'
import { storeToRefs } from 'pinia'
import md5 from 'js-md5'
const member = JSON.parse(sessionStorage.getItem('member'))
const { optionDatas } = storeToRefs(useOptionDataStore())
const isOpen = ref(true)
// 编辑成功事件/通知父组件刷新
const emit = defineEmits(['editOk', 'close'])
// 获取配置
const props = defineProps(['modal', 'editJson', 'requestApi', 'editDisables'])

// const props = defineProps({
//   modal: Object,
//   editJson: Object,
//   requestApi: Object,
//   editDisables: {
//     default: []
//   }
// })
// 初始化数据赋值
const formData = ref(props.modal)
const modalOld = JSON.parse(JSON.stringify(props.modal))
// 解除与 editJson 双向绑定，改为单向
const editJson = computed(() => JSON.parse(JSON.stringify(props.editJson)))
const requestApi = props.requestApi
const rules = ref({})
const fileList = ref({})
// const editJson = ref([
//   {
//     field: 'default',
//     label: '默认',
//     isShow: true,
//     type: {
//       value: 'select',
//       select: {
//         optionId: '',
//         options: [
//           {
//             label: '',
//             value: ''
//           }
//         ]
//       },
//       upload: {
//         size: 100,
//         type: ['txt', 'pdf'],
//         num: 1
//       }
//     },
//     gridField: null, // 绑定网格字段
//     rule: [{ required: true }]
//   }
// ])

console.log('初始化编辑数据')
jsonEdit()

function jsonEdit() {
  editJson.value.forEach((item) => {
    // 处理参数校验规则/默认值
    if (item.isShow) {
      rules.value[item.field] = eval(item.rule)()
    }
    if (item.type.value === 'json') {
      try {
        formData.value[item.field] = JSON.parse(formData.value[item.field])
      } catch (e) {
        console.error('json转换错误,非第一次打开编辑页面可忽略', e)
      }
    }
    // 获取最新选项数据
    if (item.type.value === 'select') {
      if (item.type.select.optionId) {
        useOptionDataStore().add(item.type.select.optionId)
      }
      if (item.type.select.multiple) {
        // 多选数据库字段统一设置为json格式保存
        formData.value[item.field] = JSON.parse(formData.value[item.field])
      } else {
        // 兼容select组件匹配值，int类型值无法匹配
        if (typeof formData.value[item.field] === 'number') {
          formData.value[item.field] = formData.value[item.field].toString()
        }
      }
    }
    // 将旧文件链接显示到文件上传列表
    if (item.type.value.includes('upload')) {
      const filePaths = formData.value[item.field]
      fileList.value[item.field] = []
      if (filePaths) {
        if (filePaths instanceof Array) {
          // 数组，多个文件地址
          filePaths.forEach((item2) => {
            fileList.value[item.field].push({
              name: item2.split('/').pop(),
              url: item2,
              response: { data: { url: item2 } }
            })
          })
        } else {
          // 单个文件地址
          fileList.value[item.field].push({
            name: filePaths.split('/').pop(),
            url: filePaths,
            response: { data: { url: filePaths } }
          })
        }
      }
    }
  })
}
// 关闭
function close() {
  emit('close')
}
const formRef = ref()

// 参数提交前处理
function submitHandel() {
  // 元数据
  let metaData = { ...formData.value, _member: member }
  for (const key in editJson.value) {
    const item = editJson.value[key]
    // 元数据占位符处理
    if (item.metadataPlaceholder) {
      extendPlaceholderHandle(item.field, metaData)
    }
    // 文件上传处理
    if (item.type.value.includes('upload')) {
      const files = fileList.value[item.field]
      if (files?.length > 0) {
        // 获取上传文件的限制的文件数量
        if (item.type.upload.num === 1) {
          // 文件数量等于1，设为字符串
          formData.value[item.field] = files[0].response.data.url
        } else {
          // 文件数量大于1，设为数组
          formData.value[item.field] = []
          files.forEach((item) => {
            formData.value[item.field].push(item.response.data.url)
          })
        }
      } else {
        if (item.type.upload.num === 1) {
          formData.value[item.field] = ''
        } else {
          formData.value[item.field] = []
        }
      }
    }
  }
  return true
}

// 元数据占位符处理
function extendPlaceholderHandle(key, metaData) {
  formData.value[key] = placeholder(formData.value[key], metaData)
}

// 参数校验通过后参数处理
function submitHandelCheckOk() {
  for (const key in editJson.value) {
    const item = editJson.value[key]
    // md5加密处理
    if (item.type.value === 'text' && item.type.text?.md5 && formData.value[item.field]) {
      // 判断值是否改变，否则不进行MD5加密
      if (modalOld[item.field] !== formData.value[item.field]) {
        formData.value[item.field] = md5(formData.value[item.field])
      }
    }
    if (item.type.value === 'select' && item.type.select.multiple) {
      formData.value[item.field] = JSON.stringify(formData.value[item.field])
    }
    // json数据处理
    if (item.type.value === 'json' && formData.value[item.field]) {
      formData.value[item.field] = JSON.stringify(formData.value[item.field])
    }
  }
}
// 提交
function confirmClick() {
  if (!submitHandel()) {
    return
  }
  formRef.value.validate((result) => {
    if (result) {
      submitHandelCheckOk()
      editApi()
    } else {
      ElMessage.error('参数校验不通过')
    }
  })
}

function editApi() {
  requestApi
    .edit(formData.value)
    .then((data) => {
      if (data && data.code === 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        })
        // 通知父组件刷新数据
        emit('editOk')
        // 关闭编辑页面
        close()
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
</script>
